package cn.pzaily.orange.manage.service.impl;

import cn.pzaily.orange.core.utils.StringUtils;
import cn.pzaily.orange.manage.service.SysUserLoginService;
import cn.pzaily.orange.manage.utils.JwtTokenUtils;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @PackageName: cn.pzaily.orange.manage.server.impl
 * @Description:
 * @Author: Pang
 * @Date: 2021-05-13 21:40
 */
@Service
public class SysUserLoginServiceImpl implements SysUserLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired()
    private UserDetailsService userDetailsService;

    @Override
    public String login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        String token = jwtTokenUtils.generateToken(usernamePasswordAuthenticationToken);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        return token;
    }

    @Override
    public Map<String, String> getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key, verCode, 30, TimeUnit.MINUTES);
        Map<String, String> result = new HashMap<>();
        result.put("key", key);
        result.put("image", specCaptcha.toBase64());
        return result;
    }

    @Override
    public boolean validationCaptcha(String key, String value) {
        String code = (String) redisTemplate.opsForValue().get(key);
        // 校验验证码
        if (StringUtils.isEmpty(code)) {
            return false;
        }
        if (!code.equalsIgnoreCase(value.trim())) {
            return false;
        }
        return true;
    }
}
